/**
 * @file trading_system.cpp
 * @brief Implementation of the TradingSystem class
 * 
 * This file contains the implementation of the core trading system that manages
 * all components of a high-frequency trading system including market data,
 * order management, risk management and execution.
 * 
 * @copyright Copyright (c) 2025 HFT System
 * @author Developer Name
 * @date 2023-07-15
 * @version 1.0.0
 */

#include "core/trading_system.h"
#include "utils/logger.h"
#include "market_data/market_data.h"
#include "core/order_manager.h"
#include "risk/risk_manager.h"
#include "core/execution.h"
#include <stdexcept>
#include <thread>
#include <chrono>
#include <map>

namespace hft {

/**
 * @class TradingSystem
 * @brief 高频交易系统核心管理类
 * 
 * TradingSystem类负责初始化、启动和停止交易系统的所有组件，包括：
 * - 市场数据处理
 * - 订单管理
 * - 风险管理
 * - 执行引擎
 * - 策略管理
 * 
 * 该类提供主事件循环，协调各组件间的交互，确保系统正常运行。
 * 
 * @note 使用前需要先调用initialize()初始化，然后调用start()启动系统
 */
/**
 * @brief 构造新的TradingSystem对象
 * 
 * 使用默认值初始化交易系统的所有组件。
 * 子组件的实际初始化在initialize()方法中完成。
 * 
 * @note 构造完成后系统尚未就绪。
 *       需要调用initialize()和start()才能开始交易。
 */
TradingSystem::TradingSystem() 
    : running_(false),
      should_stop_(false),
      components_initialized_(false) {
    Logger::info("Trading system instance created");
    initializeComponents();
}

TradingSystem::~TradingSystem() {
    try {
        Logger::debug("Trading system destructor called");
        
        // 确保系统已停止
        if (running_.load()) {
            Logger::info("Stopping trading system in destructor");
            stop();
        }
        
        // 显式释放资源
        Logger::debug("Releasing trading system components...");
        market_data_.reset();
        order_manager_.reset();
        risk_manager_.reset();
        execution_.reset();
        
        // 清理策略
        strategies_.clear();
        worker_threads_.clear();
        
        Logger::info("Trading system resources released successfully");
    } catch (const std::exception& e) {
        Logger::error("Exception in trading system destructor: {}", e.what());
    } catch (...) {
        Logger::error("Unknown exception in trading system destructor");
    }
}

void TradingSystem::initializeComponents() {
    if (components_initialized_) {
        Logger::warning("Components already initialized");
        return;
    }
    
    Logger::info("Initializing trading system components...");
    
    try {
        // 初始化市场数据处理组件
        market_data_ = std::make_shared<MarketData>();
        
        // 初始化订单管理组件
        order_manager_ = std::make_shared<OrderManager>();
        
        // 初始化风控管理组件
        risk_manager_ = std::make_shared<RiskManager>();
        
        // 初始化执行引擎组件
        execution_ = std::make_shared<Execution>();
        
        // 设置组件间依赖关系
        market_data_->setOrderManager(order_manager_.get());
        market_data_->setRiskManager(risk_manager_.get());
        order_manager_->setExecution(execution_.get());
        risk_manager_->setOrderManager(order_manager_.get());
        
        components_initialized_ = true;
        Logger::info("All components initialized successfully");
    } catch (const std::exception& e) {
        Logger::error("Component initialization failed: {}", e.what());
        throw;
    }
}

void TradingSystem::setRiskLimits(const RiskLimits& limits) {
    if (!risk_manager_) {
        Logger::error("Risk manager not initialized");
        return;
    }
    
    risk_manager_->setLimits(limits);
    Logger::info("Risk limits updated");
}

void TradingSystem::addStrategy(std::shared_ptr<Strategy> strategy) {
    if (!strategy) {
        Logger::error("Cannot add null strategy");
        return;
    }
    
    strategies_.push_back(strategy);
    strategy->setTradingSystem(this);
    Logger::info("Strategy added: {}", strategy->getName());
}

void TradingSystem::setOrderExecutor(std::shared_ptr<Execution> executor) {
    if (!executor) {
        Logger::error("Cannot set null executor");
        return;
    }
    
    execution_ = executor;
    if (order_manager_) {
        order_manager_->setExecution(execution_.get());
    }
    Logger::info("Order executor updated");
}

void TradingSystem::start() {
    if (running_) {
        Logger::warning("Trading system is already running");
        return;
    }
    
    // 记录初始内存使用
    auto start_mem = getCurrentMemoryUsage();
    Logger::info("Starting trading system with configuration:");
    Logger::info("  Max Order Rate: {} orders/sec", config_.max_order_rate);
    Logger::info("  Latency Threshold: {}ms", config_.latency_threshold_ms);
    Logger::info("  Risk Limits: {}", config_.risk_limits);
    Logger::info("  Initial memory usage: {} MB", start_mem / (1024 * 1024));
    
    Logger::info("Checking component status...");
    if (!components_initialized_) {
        Logger::error("Components not initialized");
        throw std::runtime_error("Cannot start: components not initialized");
    }
    
    Logger::debug("Component status:");
    Logger::debug("  Market Data: {}", market_data_ ? "Ready" : "Not Ready");
    Logger::debug("  Order Manager: {}", order_manager_ ? "Ready" : "Not Ready");
    Logger::debug("  Risk Manager: {}", risk_manager_ ? "Ready" : "Not Ready");
    Logger::debug("  Execution: {}", execution_ ? "Ready" : "Not Ready");
    
    try {
        // 启动各组件
        market_data_->start();
        order_manager_->start();
        risk_manager_->start();
        execution_->start();
        
        // 启动所有策略
        for (auto& strategy : strategies_) {
            strategy->start();
        }
        
        // 启动事件循环线程
        worker_threads_.emplace_back(&TradingSystem::eventLoop, this);
        
        running_ = true;
        Logger::info("Trading system started successfully");
    } catch (const std::exception& e) {
        Logger::error("Failed to start trading system: {}", e.what());
        stop();
        throw;
    }
}

void TradingSystem::stop() {
    if (!running_.load()) {
        Logger::warning("Trading system not running");
        return;
    }
    
    auto start_time = std::chrono::steady_clock::now();
    Logger::info("Stopping trading system...");
    should_stop_.store(true);
    event_cv_.notify_all();
    
    Logger::debug("Stopping strategies...");
    for (auto& strategy : strategies_) {
        Logger::debug("  Stopping strategy: {}", strategy->getName());
        strategy->stop();
    }
    
    Logger::debug("Stopping components...");
    if (execution_) {
        Logger::debug("  Stopping execution engine");
        execution_->stop();
    }
    if (risk_manager_) {
        Logger::debug("  Stopping risk manager");
        risk_manager_->stop();
    }
    if (order_manager_) {
        Logger::debug("  Stopping order manager");
        order_manager_->stop();
    }
    if (market_data_) {
        Logger::debug("  Stopping market data");
        market_data_->stop();
    }
    
    Logger::debug("Joining worker threads...");
    for (auto& thread : worker_threads_) {
        if (thread.joinable()) {
            thread.join();
        }
    }
    worker_threads_.clear();
    
    running_ = false;
    auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(
        std::chrono::steady_clock::now() - start_time);
    Logger::info("Trading system stopped successfully in {}ms", duration.count());
}

/**
 * @brief Main event loop of the trading system
 * 
 * This is the core event loop that continuously processes:
 * - Market data updates
 * - Order status updates
 * - System health checks
 * 
 * The loop runs until m_shouldStop is set to true. Each iteration:
 * 1. Processes incoming market data
 * 2. Handles order updates
 * 3. Performs system health check
 * 
 * @throws std::runtime_error if critical error occurs during processing
 * @note This method runs in a dedicated thread started by start()
 */
void TradingSystem::eventLoop() {
    Logger::info("Event loop started");
    
    // 动态等待时间计算
    auto calculateWaitTime = [this]() {
        const auto base_wait = std::chrono::milliseconds(1);
        const auto max_wait = std::chrono::milliseconds(100);
        
        // 根据队列负载计算等待时间
        size_t total_load = market_data_->getQueueSize() + 
                          order_manager_->getQueueSize();
        
        if (total_load > 1000) return base_wait; // 高负载时最小等待
        if (total_load > 100) return std::chrono::milliseconds(5);
        return max_wait; // 低负载时最大等待
    };

    while (!should_stop_.load(std::memory_order_relaxed)) {
        try {
            std::unique_lock<std::mutex> lock(event_mutex_);
            
            // 动态等待时间
            auto wait_time = calculateWaitTime();
            event_cv_.wait_for(lock, wait_time, 
                [this]{ return should_stop_ || hasWork(); });
            
            if (should_stop_) break;
            
            // 批处理市场数据
            size_t market_data_processed = 0;
            while (market_data_ && market_data_->getQueueSize() > 0 && 
                  market_data_processed < config_.max_batch_size) {
                processMarketData();
                ++market_data_processed;
            }
            
            // 批处理订单
            size_t orders_processed = 0;
            while (order_manager_ && order_manager_->getQueueSize() > 0 && 
                  orders_processed < config_.max_batch_size) {
                processOrders();
                ++orders_processed;
            }
            
            // 健康检查
            if (!healthCheck()) {
                Logger::error("Health check failed, stopping system");
                stop();
                break;
            }
            
            // 如果有工作未完成，立即继续处理
            if (hasWork()) {
                continue;
            }
        } catch (const std::exception& e) {
            Logger::error("Event loop error: {}", e.what());
            stop();
            break;
        }
    }
    
    Logger::info("Event loop ended");
}

void TradingSystem::processMarketData() {
    auto process_start = std::chrono::steady_clock::now();
    
    try {
        if (!market_data_) {
            Logger::warning("Market data component not available");
            return;
        }

        // 记录队列大小
        size_t queue_size = market_data_->getQueueSize();
        if (queue_size > config_.max_market_data_queue) {
            Logger::warn("Large market data queue: {} items", queue_size);
        }

        // 处理市场数据
        auto processed = market_data_->processQueue();
        
        // 记录处理耗时
        auto process_time = std::chrono::duration_cast<std::chrono::microseconds>(
            std::chrono::steady_clock::now() - process_start);
        
        metrics_.market_data_processed += processed;
        metrics_.market_data_processing_time = process_time.count();
        
        if (process_time > config_.max_processing_time) {
            Logger::warn("Slow market data processing: {}μs", process_time.count());
        }

    } catch (const std::exception& e) {
        Logger::error("Exception in processMarketData: {}", e.what());
        metrics_.market_data_errors++;
        throw;
    }
}

void TradingSystem::processOrders() {
    auto process_start = std::chrono::steady_clock::now();
    
    try {
        if (!order_manager_) {
            Logger::warning("Order manager component not available");
            return;
        }

        // 记录队列大小
        size_t queue_size = order_manager_->getQueueSize();
        if (queue_size > config_.max_order_queue) {
            Logger::warn("Large order queue: {} items", queue_size);
        }

        // 处理订单更新
        auto processed = order_manager_->processQueue();
        
        // 记录处理耗时
        auto process_time = std::chrono::duration_cast<std::chrono::microseconds>(
            std::chrono::steady_clock::now() - process_start);
        
        metrics_.orders_processed += processed;
        metrics_.order_processing_time = process_time.count();
        
        if (process_time > config_.max_processing_time) {
            Logger::warn("Slow order processing: {}μs", process_time.count());
        }

    } catch (const std::exception& e) {
        Logger::error("Exception in processOrders: {}", e.what());
        metrics_.order_errors++;
        throw;
    }
}

void TradingSystem::onMarketData(const MarketData& data) {
    if (!running_.load(std::memory_order_relaxed)) return;
    
    auto process_start = std::chrono::steady_clock::now();
    
    try {
        // 防御性检查
        if (!market_data_) {
            Logger::error("Market data component not available");
            return;
        }
        
        // 更新市场数据
        market_data_->update(data);
        
        // 按策略类型分组并行执行
        const size_t group_size = 4; // 每组4个策略
        size_t num_groups = (strategies_.size() + group_size - 1) / group_size;
        
        // 并行处理策略组
        #pragma omp parallel for
        for (size_t group = 0; group < num_groups; ++group) {
            size_t start = group * group_size;
            size_t end = std::min(start + group_size, strategies_.size());
            
            for (size_t i = start; i < end; ++i) {
                try {
                    auto& strategy = strategies_[i];
                    auto strategy_start = std::chrono::steady_clock::now();
                    
                    strategy->onMarketData(data);
                    
                    auto duration = std::chrono::duration_cast<std::chrono::microseconds>(
                        std::chrono::steady_clock::now() - strategy_start);
                    strategy->recordExecutionTime(duration.count());
                } catch (const std::exception& e) {
                    Logger::error("Strategy {} error: {}", 
                        strategies_[i]->getName(), e.what());
                    metrics_.strategy_errors++;
                }
            }
        }
        
        // 记录总处理时间
        auto process_time = std::chrono::duration_cast<std::chrono::microseconds>(
            std::chrono::steady_clock::now() - process_start);
        metrics_.market_data_processing_time = process_time.count();
        
    } catch (const std::exception& e) {
        Logger::error("Exception in onMarketData: {}", e.what());
        metrics_.market_data_errors++;
        throw;
    }
}

void TradingSystem::onOrderBookUpdate(const OrderBook& orderBook) {
    if (!running_) return;
    
    // 防御性检查
    if (!market_data_) {
        Logger::error("Market data component not available");
        return;
    }
    
    try {
        // 更新订单簿
        market_data_->updateOrderBook(orderBook);
        
        // 通知所有策略
        for (auto& strategy : strategies_) {
            if (strategy) {
                try {
                    strategy->onOrderBookUpdate(orderBook);
                } catch (const std::exception& e) {
                    Logger::error("Strategy {} error in onOrderBookUpdate: {}", 
                        strategy->getName(), e.what());
                    metrics_.strategy_errors++;
                }
            }
        }
    } catch (const std::exception& e) {
        Logger::error("Exception in onOrderBookUpdate: {}", e.what());
        metrics_.market_data_errors++;
    }
}

void TradingSystem::onOrderUpdate(const Order& order) {
    if (!running_) return;
    
    Logger::debug("Order update: {} {}@{} (ID:{}) Status:{}", 
        order.side == Side::Buy ? "Buy" : "Sell",
        order.quantity,
        order.price,
        order.orderId,
        order.status);
    
    // 防御性检查
    if (!order_manager_) {
        Logger::error("Order manager component not available");
        return;
    }
    
    try {
        // 更新订单状态
        order_manager_->updateOrder(order);
        
        // 并行通知相关策略
        #pragma omp parallel for
        for (size_t i = 0; i < strategies_.size(); ++i) {
            auto& strategy = strategies_[i];
            if (strategy && strategy->getStrategyId() == order.strategyId) {
                try {
                    auto start = std::chrono::steady_clock::now();
                    strategy->onOrderUpdate(order);
                    auto duration = std::chrono::duration_cast<std::chrono::microseconds>(
                        std::chrono::steady_clock::now() - start);
                    strategy->recordExecutionTime(duration.count());
                } catch (const std::exception& e) {
                    Logger::error("Strategy {} error in onOrderUpdate: {}", 
                        strategy->getName(), e.what());
                    metrics_.strategy_errors++;
                }
            }
        }
    } catch (const std::exception& e) {
        Logger::error("Exception in onOrderUpdate: {}", e.what());
        metrics_.order_errors++;
    }
}

void TradingSystem::onOrderFilled(const Trade& trade) {
    if (!running_) return;
    
    Logger::info("Order filled: {} {}@{}", 
        trade.side == Side::Buy ? "Buy" : "Sell",
        trade.quantity,
        trade.price);
    
    // 防御性检查
    if (!order_manager_) {
        Logger::error("Order manager component not available");
        return;
    }
    
    try {
        // 更新持仓和PnL
        order_manager_->updatePosition(trade);
        
        // 通知相关策略
        for (auto& strategy : strategies_) {
            if (strategy && strategy->getStrategyId() == trade.strategyId) {
                try {
                    strategy->onOrderFilled(trade);
                } catch (const std::exception& e) {
                    Logger::error("Strategy {} error in onOrderFilled: {}", 
                        strategy->getName(), e.what());
                    metrics_.strategy_errors++;
                }
            }
        }
    } catch (const std::exception& e) {
        Logger::error("Exception in onOrderFilled: {}", e.what());
        metrics_.order_errors++;
    }
}

void TradingSystem::onOrderCancelled(const Order& order) {
    if (!running_) return;
    
    Logger::info("Order cancelled: {} {}@{} (ID:{})", 
        order.side == Side::Buy ? "Buy" : "Sell",
        order.quantity,
        order.price,
        order.orderId);
    
    // 防御性检查
    if (!order_manager_) {
        Logger::error("Order manager component not available");
        return;
    }
    
    try {
        // 更新订单状态
        order_manager_->cancelOrder(order);
        
        // 并行通知相关策略
        #pragma omp parallel for
        for (size_t i = 0; i < strategies_.size(); ++i) {
            auto& strategy = strategies_[i];
            if (strategy && strategy->getStrategyId() == order.strategyId) {
                try {
                    auto start = std::chrono::steady_clock::now();
                    strategy->onOrderCancelled(order);
                    auto duration = std::chrono::duration_cast<std::chrono::microseconds>(
                        std::chrono::steady_clock::now() - start);
                    strategy->recordExecutionTime(duration.count());
                } catch (const std::exception& e) {
                    Logger::error("Strategy {} error in onOrderCancelled: {}", 
                        strategy->getName(), e.what());
                    metrics_.strategy_errors++;
                }
            }
        }
    } catch (const std::exception& e) {
        Logger::error("Exception in onOrderCancelled: {}", e.what());
        metrics_.order_errors++;
    }
}

bool TradingSystem::healthCheck() {
    // 检查各组件状态
    bool marketDataOk = market_data_ && market_data_->isHealthy();
    bool orderManagerOk = order_manager_ && order_manager_->isHealthy();
    bool riskManagerOk = risk_manager_ && risk_manager_->isHealthy();
    bool executionOk = execution_ && execution_->isHealthy();
    
    // 记录健康状态
    if (!marketDataOk) Logger::warning("Market data component unhealthy");
    if (!orderManagerOk) Logger::warning("Order manager component unhealthy");
    if (!riskManagerOk) Logger::warning("Risk manager component unhealthy");
    if (!executionOk) Logger::warning("Execution component unhealthy");
    
    return marketDataOk && orderManagerOk && riskManagerOk && executionOk;
}

std::map<std::string, double> TradingSystem::getRiskMetrics() const {
    if (!risk_manager_) {
        return {};
    }
    return risk_manager_->getMetrics();
}

double TradingSystem::getTotalPnL() const {
    if (!order_manager_) {
        return 0.0;
    }
    return order_manager_->getTotalPnL();
}

std::map<std::string, Position> TradingSystem::getPositions() const {
    if (!order_manager_) {
        return {};
    }
    return order_manager_->getPositions();
}

} // namespace hft